package westh.ilib.struts.action.myTagCloud;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.mule.extras.client.MuleClient;
import org.mule.umo.UMOMessage;

import westh.config.Config;
import westh.ilib.bean.croDomainSearch.Author;
import westh.ilib.bean.tagBean.TagSys;

/**
 * @author ChaiLinglu
 * @ModifyDate 2010-09-07
 * @modifier ChaiLinglu
 * @content refine
 * 
 * @modified zhangjian
 * @date 2010-09-16
 * @content modified clouds address
 * 
 * @ModifyDate 2010-09-17
 * @modifier ChaiLinglu
 * @content modify resource's author display and download url
 * 
 * @modified by yanglei
 * @date 2010-09-28
 * @content add pagination
 * @modified by yanglei
 * @date 2010-09-29
 * @content fix bugs
 */
public class GetRscInfoAction extends Action {
	private final static Log log = LogFactory.getLog(GetRscInfoAction.class);
	//get clouds Ip address
	String localhostUrl = Config.get("localhostUrl");
	String remoteUrl = Config.get("remoteUrl");
	
	public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {

		DynaActionForm f = (DynaActionForm) form;
		
		//get data from page
		String userId=request.getRemoteUser();
		userId="ebb70a6400e64872ad24fe5a9da30c2c";/////////////////////////////////////////tempTest
		String rscId=request.getParameter("rscId");
		log.debug("RSCID:"+rscId);

		//create input json for tagsysCloud
		JSONObject tagJson=new JSONObject();
		tagJson.put("rscId", rscId);
		
		//create input json for westdoCloud
		JSONObject inJson = new JSONObject();  //rulesControl
		JSONObject inStr = new JSONObject();   //direct call
		inStr.put("rscId", rscId);
		inJson.put("methodName", "getRscInfoById");//rulesControl
		inJson.put("jsonStr", inStr);//rulesControl
		
		// call webService  --  CDO
		String outString = "";
		try {
			MuleClient clientD = new MuleClient();
			UMOMessage umo = clientD.send("axis:http://"+localhostUrl+":4381/LIBJson/iDlibJson?method=getRscInfoById",inStr.toString(), null);
			outString = (String) umo.getPayload();
			log.debug("getRscInfoById:Output:CDO:"+outString);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		// call webService  --  tagsysCloud
		log.debug("getTagLog:INPUT:TAGSYSCLOUD:"+tagJson.toString());
		String outTagString = "";
		try {
			MuleClient client = new MuleClient();
			UMOMessage umo = client.send("axis:http://"+remoteUrl+":4481/DataCenter/TagDataCenter?method=getTagLog",tagJson.toString(),null);
			outTagString = (String)umo.getPayload();
			log.debug("getTagListById:Output:tagsysCloud:"+outTagString);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		String retCode=""; //return retCode
		String retMsg="";// return messages
		String returnStr=""; // define the String which mapping invoke

		List authorList=new ArrayList();
		List list = new ArrayList();
		Set<String> tagNames = new HashSet<String>();
		TagSys tagsys = new TagSys();
		
		JSONObject jsonOut= JSONObject.fromObject(outTagString);
		retCode = jsonOut.getString("retCode");
		
		if (retCode.equals("5500")) {
			String result = jsonOut.getString("result");
			JSONArray resultArry = JSONArray.fromObject(result);
			log.info("JSONArray="+resultArry.size());
			
			//if it contains articles ,go on
			if(resultArry.size() > 0){
				
				//get the last article
				JSONObject lastTagContent = JSONObject.fromObject(resultArry.get(resultArry.size()-1));
				TagSys lastTagSys = new TagSys();
				lastTagSys.setComments(lastTagContent.getString("rscDesc"));
				lastTagSys.setTagName(lastTagContent.getString("rscTag"));
				lastTagSys.setRscScore(lastTagContent.getString("rscScore"));
				lastTagSys.setTagUser(lastTagContent.getString("userId"));
				lastTagSys.setReadStatus(lastTagContent.getString("readstatus"));
				
				String averScore = lastTagContent.getString("rscAvgScore");
				Float averScoreFloat = Float.valueOf(averScore);
				int averScoreInt = (int)(averScoreFloat*10);
				averScoreFloat = ((float)averScoreInt/10);
				log.debug("rscScore : " + averScoreFloat);
				lastTagSys.setAverScore(averScoreFloat + "");
				request.setAttribute("lastTagSys", lastTagSys);
				
				for(int i = resultArry.size()-1; i >=0 ; i--){
					JSONObject jsonOut2 = JSONObject.fromObject(resultArry.get(i));
					tagsys = new TagSys();
					
					String comments=jsonOut2.getString("rscDesc");
					String tag=jsonOut2.getString("rscTag");
					String score=jsonOut2.getString("rscScore");
					String face=jsonOut2.getString("face");
					String time=jsonOut2.getString("time");
					String readStatus=jsonOut2.getString("readstatus");
					if(readStatus.equals("0")){
						readStatus="未读";
					}
					if(readStatus.equals("1")){
						readStatus="在读";
					}
					if(readStatus.equals("2")){
						readStatus="已读";
					}
					if(readStatus.equals("3")){
						readStatus="要读";
					}
					tagsys.setAvgScore(jsonOut2.getString("rscAvgScore"));
					tagsys.setTagName(jsonOut2.getString("rscTag"));
					tagsys.setRscDescription(jsonOut2.getString("rscDesc"));
					tagsys.setRscScore(jsonOut2.getString("rscScore"));
					
					//if one user get more than 2 tags , spit them out
					String[] tags = tag.split(" ");
					for(String tagName : tags){
						tagNames.add(tagName);
					}
					
					tagsys.setComments(comments);
					tagsys.setTagUser(jsonOut2.getString("userId"));//
					tagsys.setReadStatus(readStatus);
					tagsys.setTime(time);
					list.add(tagsys);
				}
				
				String pageNoStr = request.getParameter("pageNo");
				
				//some fields in pagination
				int currentPageNo = 1;
				int countPages = 1;
				if(pageNoStr != null && !pageNoStr.equals("")){
					currentPageNo = Integer.parseInt(pageNoStr);
				}
	
				//count the amount of articles
				int listSize = list.size();
				
				if(listSize%10 == 0){
					countPages = listSize/10;
				} else {
					countPages = listSize/10 + 1;
				}
				
				if(currentPageNo > countPages || currentPageNo < 1){
					currentPageNo = 1;
				}
				
				if(listSize > 10){
					if(listSize >= 10*currentPageNo){
						list = list.subList((currentPageNo-1)*10, 10*currentPageNo-1);
					} else {
						list = list.subList((currentPageNo-1)*10-1, listSize-1);
					}
				}
				
				request.setAttribute("countPages", countPages);
				request.setAttribute("currentPageNo", currentPageNo);
				request.setAttribute("listSize", list.size());
				request.setAttribute("list", list);
				request.setAttribute("tagNames", tagNames);
			} else {
				request.setAttribute("contentIsNull", "true");
			}
			
			JSONObject jsonCDOOut= JSONObject.fromObject(outString);
			//0: had records,1 : nothing
			if("0".equals(jsonCDOOut.getString("retCode"))){
				JSONObject resultJSONCDO = JSONObject.fromObject(jsonCDOOut.getString("result"));
				
				String type="";
				if(resultJSONCDO.getString("rscType").equals("1")){
					type="图书 ";
				}
				if(resultJSONCDO.getString("rscType").equals("2")){
					type="会议论文 ";
				}
				if(resultJSONCDO.getString("rscType").equals("3")){
					type="期刊论文 ";
				}
				if(resultJSONCDO.getString("rscType").equals("4")){
					type="专利 ";
				}
				if(resultJSONCDO.getString("rscType").equals("5")){
					type="标准 ";
				}
				if(resultJSONCDO.getString("rscType").equals("6")){
					type="软著 ";
				}
				if(resultJSONCDO.getString("rscType").equals("7")){
					type="技术报告";
				}
				String field = "";
				String rscField=resultJSONCDO.getString("rscField");
				if(rscField.equals("1")){
					field="国家图书馆";
				} else if(rscField.equals("2")){
					field="清华图书馆（OAI）";
				} else if(rscField.equals("3")){
					field="CALIS";
				} else if(rscField.equals("4")){
					field="清华大学水利";
				} else if(rscField.equals("5")){
					field="TagSys";
				}
				
				//get all authors
				Author firstAuthor=new Author();
				Author [] otherAuthors=null;
				String rscFirstAuthorStr = resultJSONCDO.getString("rscFirstAuthor");
				if(!rscFirstAuthorStr.equals("")){
					JSONObject rscFirstAuthorObj =  JSONObject.fromObject(rscFirstAuthorStr);
					firstAuthor.setName(rscFirstAuthorObj.getString("name"));
					
					firstAuthor.setUid(rscFirstAuthorObj.getString("uid"));
					//firstAuthor.setIeeeRefid(rscFirstAuthorObj.getString("ieeeRefid"));
					firstAuthor.setInstitution(rscFirstAuthorObj.getString("institution"));
					authorList.add(firstAuthor);
				}
				
				String rscOtherAuthorsStr = resultJSONCDO.getString("rscOtherAuthors");
				if(!rscOtherAuthorsStr.equals("")){
					JSONArray rscOtherAuthorsObj =  JSONArray.fromObject(rscOtherAuthorsStr);
				
					int otherAuthorCount=rscOtherAuthorsObj.size();
					otherAuthors=new Author[otherAuthorCount];
				
					for(int i=0;i<otherAuthorCount;i++)
					{
						Author author=new Author();
						JSONObject rscAuthorObj=JSONObject.fromObject(rscOtherAuthorsObj.get(i));
						author.setName(rscAuthorObj.getString("name"));
						author.setUid(rscAuthorObj.getString("uid"));
						//author.setIeeeRefid(rscAuthorObj.getString("ieeeRefid"));
						author.setInstitution(rscAuthorObj.getString("institution"));
						otherAuthors[i]=author;
						authorList.add(otherAuthors[i]);
					}
				}
				
				request.setAttribute("authorList", authorList);
				
				tagsys.setAuthor(resultJSONCDO.getString("rscCreator"));
				tagsys.setRscKeyWord(resultJSONCDO.getString("rscTitle"));
				tagsys.setType(type);
				tagsys.setRscId(resultJSONCDO.getString("rscId"));
				tagsys.setRscTitle(resultJSONCDO.getString("rscTitle").replaceAll("&amp;", "&").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&apos;", "'").replaceAll("&quot;", "\""));
				tagsys.setRscSummary(resultJSONCDO.getString("rscAbstract"));
				tagsys.setRscPublishDate(resultJSONCDO.getString("rscPublishDate"));
				tagsys.setRscAuthor(resultJSONCDO.getString("rscCreator"));
				tagsys.setRscType(resultJSONCDO.getString("rscType"));
				tagsys.setField(field);
				tagsys.setRscUrl(resultJSONCDO.getString("rscUrl").replaceAll("&amp;", "&").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&apos;", "'").replaceAll("&quot;", "\""));
				tagsys.setRscDate(resultJSONCDO.getString("rscPublishDate"));
				tagsys.setRscSource(resultJSONCDO.getString("rscSource").replaceAll("&amp;", "&").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&apos;", "'").replaceAll("&quot;", "\""));
				tagsys.setRscId(rscId);
				
				request.setAttribute("rsc", tagsys);
				
				returnStr = "succ";
			} else {
				request.setAttribute("info", "该ID未找到对应的信息!");
				returnStr = "fail";
			}
			
		} else {
			retMsg = jsonOut.getString("retMsg");
			request.setAttribute("info", retMsg);
			returnStr = "fail";
		}
		request.setAttribute("rscId", rscId);
		return mapping.findForward(returnStr);
	}
}
